package date

import (
	"fmt"
	"time"
)

const (
	time_format      = "2006-01-02 15:04:05" //golang中的时间格式写法
	hyai_time_format = "2006-01-02 15:04"    //本项目的时间格式
	day_format       = "2006-01-02"          //当天
)

//获取当天
func NowDay() string {
	return time.Now().Format(day_format)
}

//获取当前时间
func Now() string {
	return time.Now().Format(time_format)
}

//获取当前时间戳 精确到秒
func TimeUnix() int64 {
	return time.Now().Unix()
}

func DateToUnix(date string) (int64, error) {
	loc, _ := time.LoadLocation("Asia/Chongqing")
	res, err := time.ParseInLocation("2006-01-02 15:04:05", date, loc)
	return res.Unix(), err
}

//获取当前时间戳 精确到毫秒
func TimeUnixNano() int64 {
	return time.Now().UnixNano()
}

//时间戳转换为时间字符串
func TimeUnixToStr(timeUnix int64) string {
	return time.Unix(timeUnix, 0).Format(hyai_time_format)
}

//时间戳转换为时间字符串
func TimeDayUnixToStr(timeUnix int64) string {
	return time.Unix(timeUnix, 0).Format(day_format)
}

//字符串转换为时间对象
func StrToTime(timeStr string) time.Time {
	loc, _ := time.LoadLocation("Asia/Chongqing")
	res, err := time.ParseInLocation("2006-01-02 15:04:05", timeStr, loc)
	if err != nil {
		return time.Time{}
	}
	return res
}

//根据生日获取年龄
func GetAge(date string) uint8 {
	d, err := time.Parse(day_format, date)
	if err != nil {
		fmt.Println(err, date+" to date parse failed!")
		return 0
	}
	year := d.Year()
	month := int(d.Month())
	day := d.Day()
	nowYear := time.Now().Year()
	nowMonth := int(time.Now().Month())
	nowDay := time.Now().Day()
	res := nowYear - year
	if nowMonth < month {
		return uint8(res - 1)
	}
	if nowMonth == month && nowDay < day {
		return uint8(res - 1)
	}
	return uint8(res)
}
